#include <iostream>
#include <sstream>
#include <SFML/Graphics/RenderWindow.hpp>
#include <nice2d/macros.h>
#include <nice2d/scene.h>
#include <nice2d/tilemap.h>
#include <nice2d/background.h>
#include <nice2d/imagedescriptor.h>
#include <nice2d/components/imagemanager.h>
#include <nice2d/util.h>

#define SCENE_WIDTH  960.0f
#define SCENE_HEIGHT 640.0f

class UnitScene : public Scene, public TileVisitor
{
public:
    void onInitialed()override
    {
        setSceneBox({0.0f, 0.0f, SCENE_WIDTH, SCENE_HEIGHT});

        tileMap = TileMap::create(TileMapType::TileMapType_Grid);
        tileMap->init(17, 10, 72.0f);

        descriptor = std::make_shared<ImageDescriptor>();
        bool ok = descriptor->load("./../data/tiles/tileset2.xml");
        if (!ok) {
            auto text = createToastText();
            text->setText("load ./../data/tiles/tileset.xml failed");
            addChild(text);
        }

        auto imageManager = GET_APPLICATION_COMPONENT(ImageManager);

        tileMap->accept([&](uint32_t x, uint32_t y, std::shared_ptr<Tile> tile) {
            int size = descriptor->areas.size();
            auto texture = imageManager->loadTextureFromFile(descriptor->file,
                                                             descriptor->areas[rand() % size]);
            tile->setTexture(texture.get());
        });
        addChild(tileMap);
        tileMap->accept(this);

        tileMap->tileClicked.connect([&](int32_t x, int32_t y) {
            auto tile = tileMap->getTileByIndex(x, y);
            if (tile)
                tile->setFillColor(darken(sf::Color::White, 0.2f));
        });

        auto text = createToastText();
        addChild(text);
        text->setBackgroundColor(sf::Color::Black);
        text->setText(L"click tile to chang tile color");
    }

    void visit(int32_t x, int32_t y, std::shared_ptr<Tile> tile) override
    {
        tile->setFillColor(sf::Color::White);
    }
private:
    std::shared_ptr<TileMap> tileMap;
    std::shared_ptr<ImageDescriptor> descriptor;
};

DECLARE_MAIN_FUNCTION_WITH_SCENE(SCENE_WIDTH, SCENE_HEIGHT, "unit10", UnitScene)
